package com.example.ble_20220504;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanResult;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

/**
 * 主页面
 */
public class MainActivity extends AppCompatActivity {
    //请求打开蓝牙
    private static final int REQUEST_ENABLE_BLUETOOTH = 100;
    //权限请求码
    private static final int REQUEST_PERMISSION_CODE = 9527;
    //蓝牙适配器
    private BluetoothAdapter bluetoothAdapter;

    //列表适配器
    private ListAdpter listAdpter;

    //设备列表
    private List<BleDevice> bleDeviceList;

    //列表项
    private ListView listView;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        requestPermission();
        openBluetooth();

    }

    //操控UI线程
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case BluetoothGatt.GATT_SUCCESS:
                    showMsg("蓝牙连接成功");
                    break;
            }
        }

    };

    //扫描设备回调
    private BluetoothAdapter.LeScanCallback leScanCallback = new BluetoothAdapter.LeScanCallback() {
        @Override
        public void onLeScan(BluetoothDevice device, int rssi, byte[] scanRecord) {
            Log.d("已扫描到的设备：", device.getName()+" "+device.getAddress() + " "+rssi);
            String rss = Integer.toString(rssi);
            BleDevice bleDevice = new BleDevice(device.getName(),device.getAddress(), rss,device);
            if (!bleDeviceList.contains(bleDevice)){
                listAdpter.add(bleDevice);
            }
        }
    };

    /**
     * 初始化蓝牙列表
     */
    private void initView(){
        listView = (ListView)findViewById(R.id.list_item);
        bleDeviceList = new ArrayList<>();
        listAdpter = new ListAdpter(MainActivity.this,R.layout.list_view,bleDeviceList);
        listView.setAdapter(listAdpter);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                  BluetoothDevice bluetoothDevice = listAdpter.getItem(position).getBluetoothDevice();
//                  BluetoothGatt bluetoothGatt = bluetoothDevice.connectGatt(MainActivity.this,false,bluetoothGattCallback);
//                  bluetoothGatt.connect();
                 Intent intent = new Intent(MainActivity.this,DeviceActivity.class);
                 intent.putExtra("device",bluetoothDevice);
                 startActivity(intent);
            }
        });
    }

    /**
     * 创建菜单
     * @param menu
     * @return
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(Menu.NONE,Menu.FIRST,0,"开始扫描");
        menu.add(Menu.NONE,2,0,"停止扫描");
        return super.onCreateOptionsMenu(menu);
    }

    /**
     * 菜单选择
     * @param item
     * @return
     */
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case Menu.FIRST:
                bleDeviceList.clear();
                listAdpter.clear();
                //开始扫描
                bluetoothAdapter.startLeScan(leScanCallback);
                //扫描10s后停止扫描
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        bluetoothAdapter.stopLeScan(leScanCallback);
                    }
                },10000);
                break;
            case 2:
                bluetoothAdapter.stopLeScan(leScanCallback);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    //是否打开蓝牙
    public void openBluetooth(){
        //获取蓝牙适配器
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        if (bluetoothAdapter != null){//是否支持蓝牙
             if(bluetoothAdapter.isEnabled()){
                 //蓝牙已打开
                 showMsg("蓝牙已打开");
             }else{
                 startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE),REQUEST_ENABLE_BLUETOOTH);
             }
        }else{
            //设备不支持蓝牙
            showMsg("设备不支持蓝牙");
        }
    }

    /**
     * Toast提示
     */
    private void showMsg(String msg){
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 页面返回结果
     */
    protected void onActivityResult(int requestCode,int resultCode,Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK){
            if (requestCode == REQUEST_ENABLE_BLUETOOTH){
                if (bluetoothAdapter.isEnabled()){
                    //蓝牙已打开
                    showMsg("蓝牙打开成功");
                }else{
                    showMsg("请打开蓝牙");
                }
            }
        }
    }

    //动态权限申请
    private void requestPermission(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
            String[] perms ={Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION};
            if (ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED
            || ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
                ActivityCompat.requestPermissions(MainActivity.this,perms,REQUEST_PERMISSION_CODE);
            }
        }
    }

    //权限申请结果返回
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE){
            for (int i = 0;i<permissions.length;i++){
                if (ContextCompat.checkSelfPermission(MainActivity.this,permissions[i]) != PackageManager.PERMISSION_GRANTED){
                    showMsg("权限申请失败");
                }else{
                    showMsg("权限申请成功");
                }
            }
        }
    }


}